// WebGL工具类
export class WebGLUtils {
  private gl: WebGLRenderingContext

  constructor(gl: WebGLRenderingContext) {
    this.gl = gl
  }

  // 创建着色器
  createShader(type: number, source: string): WebGLShader | null {
    const shader = this.gl.createShader(type)
    if (!shader) {
      console.error('Failed to create shader')
      return null
    }

    this.gl.shaderSource(shader, source)
    this.gl.compileShader(shader)

    if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
      console.error('Failed to compile shader:', this.gl.getShaderInfoLog(shader))
      this.gl.deleteShader(shader)
      return null
    }

    return shader
  }

  // 创建着色器程序
  createProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader): WebGLProgram | null {
    const program = this.gl.createProgram()
    if (!program) {
      console.error('Failed to create shader program')
      return null
    }

    this.gl.attachShader(program, vertexShader)
    this.gl.attachShader(program, fragmentShader)
    this.gl.linkProgram(program)

    if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {
      console.error('Failed to link program:', this.gl.getProgramInfoLog(program))
      return null
    }

    return program
  }

  // 创建并初始化缓冲区
  createBuffer(data: Float32Array): WebGLBuffer | null {
    const buffer = this.gl.createBuffer()
    if (!buffer) {
      console.error('Failed to create buffer')
      return null
    }

    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, buffer)
    this.gl.bufferData(this.gl.ARRAY_BUFFER, data, this.gl.STATIC_DRAW)
    return buffer
  }

  // 设置顶点属性
  setVertexAttribute(program: WebGLProgram, attributeName: string, size: number): void {
    const location = this.gl.getAttribLocation(program, attributeName)
    this.gl.vertexAttribPointer(location, size, this.gl.FLOAT, false, 0, 0)
    this.gl.enableVertexAttribArray(location)
  }
}

// 二维向量工具类
export class vec2 {
  x: number
  y: number

  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }

  // 向量插值
  static lerp(a: vec2, b: vec2, t: number): vec2 {
    return new vec2(
      a.x + (b.x - a.x) * t,
      a.y + (b.y - a.y) * t
    )
  }

  // 向量旋转
  static rotate(point: vec2, center: vec2, angle: number): vec2 {
    const dx = point.x - center.x
    const dy = point.y - center.y
    const cos = Math.cos(angle)
    const sin = Math.sin(angle)
    return new vec2(
      center.x + dx * cos - dy * sin,
      center.y + dx * sin + dy * cos
    )
  }
}

// 颜色转换工具
export const colorUtils = {
  // 将十六进制颜色转换为RGB
  hexToRgb(hex: string) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16) / 255,
      g: parseInt(result[2], 16) / 255,
      b: parseInt(result[3], 16) / 255
    } : { r: 0, g: 0, b: 0 }
  }
}
